package ua.kharkov.knure.pereverziev.diploma.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.web.command.Command;
import ua.kharkov.knure.pereverziev.diploma.web.command.CommandsContainer;

/**
 * Main servlet controller.
 * 
 * @author A.Pereverziev
 * 
 */
@SuppressWarnings("serial")
public class Controller extends HttpServlet {

	private static final Logger log = Logger.getLogger(Controller.class);

	CommandsContainer commands = CommandsContainer.getInstance();

	@Override
	protected void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		process(request, response);
	}

	@Override
	protected void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		process(request, response);
	}

	/**
	 * Main method of this controller.
	 */
	private void process(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {
		log.debug("Controller starts");
		long start = System.currentTimeMillis();
		// extract command name from the request
		final String commandName = request.getParameter("command");
		log.debug("Request parameter: command --> " + commandName);

		// obtain command object by its name
		final Command command = commands.get(commandName);
		log.debug("Obtained command --> " + command);

		// execute command and get forward address
		final String forward = command.execute(request, response);
		log.debug("Forward address --> " + forward);

		// if the forward address is not null go to the address
		if (forward != null && !"".equals(forward)) {
			final RequestDispatcher disp = request
					.getRequestDispatcher(forward);
			disp.forward(request, response);
		} else {
			ReportDownload rd = (ReportDownload) getServletConfig()
					.getServletContext().getServlet("Default");
			rd.doGet(request, response);
		}
		log.debug("Controller finished processing command " + commandName
				+ " Time: " + (start - System.currentTimeMillis()));
	}

	public CommandsContainer getCommands() {
		return commands;
	}

	public void setCommands(final CommandsContainer commands) {
		this.commands = commands;
	}

}
